import React, { useEffect, useMemo, useState } from 'react';
import { ICartReturn } from '../goods/types';
import { fetchCartList } from '@/api/cart';
import CartContainer from '../carts/cartsList/components/cartContainer';
import styled from './index.module.css';
import Footer from '../carts/cartsList/components/footer';
import { fetchSubmitOrder } from '@/api/order';
import { IResponse } from '@/types';
import { Order, Pay, PayReturn } from './type';
import { Empty, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { fetchPay } from '@/api/pay';
export default function Settlement() {
    const [cartList, setCartList] = useState<ICartReturn[]>([]);
    const nav = useNavigate();
    useEffect(() => {
        fetchCartList<ICartReturn[]>().then((res) => {
            setCartList(res.filter((item) => item.is_select));
        });
    }, []);
    const totalPrice = useMemo(() => {
        let total = 0;
        cartList.forEach((item) => {
            total += (item.good.price || item.good.oldPrice || 0) * item.num;
        });
        return total.toFixed(2);
    }, [cartList]);
    const settlement = async () => {
        // 创建订单
        try {
            let res = await fetchSubmitOrder<Order, IResponse>({
                total_price: Number(totalPrice),
                status: 1,
            });
            if (res.statusCode === 200) {
                // 发起支付
                fetchPay<Pay, IResponse<string>>({
                    orderId: res.data.id,
                    totalPrice: totalPrice,
                    returnUrl: window.location.origin + '/order/payRes?orderId=' + res.data.id,
                }).then((res) => {
                    if (res.statusCode === 200) {
                        if (res.data) {
                            window.location.href = res.data;
                        }
                    } else {
                        message.error(res.message);
                    }
                });
            } else {
                message.error(res.message);
            }
        } catch (error: any) {
            message.error(error.message);
        }
    };

    return (
        <div className={styled.settlement}>
            {cartList.length > 0 ? (
                <>
                    <h3
                        style={{
                            fontSize: '14px',
                            margin: '10px 0',
                        }}
                    >
                        Confirm order information
                    </h3>
                    <CartContainer cartList={cartList} showSelect={false}></CartContainer>
                    <Footer
                        title="Settle A ccounts"
                        totalPrice={Number(totalPrice)}
                        settlement={settlement}
                    ></Footer>
                </>
            ) : (
                <Empty />
            )}
        </div>
    );
}
